package verify;

import com.appleyk.core.model.LicenseExtraParam;
import com.appleyk.core.service.AServerInfos;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.util.Base64;

/**
 * @Author: WangYao
 * @description:
 * @date: 2024-05-08 14:45
 */
public class ServerInfo {
    private static final String key = "mySecretKey123456";

    public static void main(String[] args) throws Exception {
        LicenseExtraParam serverInfos = AServerInfos.getServer("").getServerInfos();

        //对象序列化为json
        String jsonString = serverInfos.toJsonString();
        System.out.println("原始数据 = "+jsonString);
        //加密
        String encryptedJson = encrypt(jsonString);
        System.out.println("加密后 = " + encryptedJson);
        // 解密
        String decryptedJson = decrypt(encryptedJson);
        System.out.println("解密后 = " + decryptedJson);
        // 比较解密后的字符串与原始字符串
        if (jsonString.equals(decryptedJson)) {
            System.out.println("解密后的字符串与原始字符串相同");
        } else {
            System.err.println("解密后的字符串与原始字符串不同");
        }

        // 断言
        assert jsonString.equals(decryptedJson) : "解密后的字符串与原始字符串不匹配";

        // 反序列化为对象
        ObjectMapper mapper = new ObjectMapper();
        LicenseExtraParam licenseParam = null;
        licenseParam = mapper.readValue(decryptedJson, LicenseExtraParam.class);
        // 标记为null的字段需要特殊处理
        if ("null".equals(licenseParam.getRegisterAmount())) {
            licenseParam.setRegisterAmount(null);
        }
        System.out.println("licenseParam = " + licenseParam);
    }

    public static String encrypt(String json) throws Exception {
        byte[] keyBytes = key.getBytes();
        MessageDigest sha = MessageDigest.getInstance("SHA-256");
        keyBytes = sha.digest(keyBytes);
        keyBytes = java.util.Arrays.copyOf(keyBytes, 16);
        SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(json.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String encryptedJson) throws Exception {
        byte[] keyBytes = key.getBytes();
        MessageDigest sha = MessageDigest.getInstance("SHA-256");
        keyBytes = sha.digest(keyBytes);
        keyBytes = java.util.Arrays.copyOf(keyBytes, 16);
        SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedJson);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes);
    }

}
